from typing import Any
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from db.database import Base

db = SQLAlchemy()


# Define your models here
class LLM_MODEL(db.Model, Base):
    # 表名为llm_model
    __name__ = 'llm_model'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(255), nullable=True)
    base_url = db.Column(db.String(255), nullable=False)
    api_key = db.Column(db.String(255), nullable=True)
    add_user = db.Column(db.String(100), nullable=False)
    requests_url = db.Column(db.String(50), nullable=True)

    # Add other fields as necessary

    def __init__(self, name, description, base_url, api_key, requests_url, **kw: Any):
        super().__init__(**kw)
        self.name = name
        self.description = description
        self.base_url = base_url
        self.api_key = api_key
        self.add_user = 'admin'
        self.requests_url = requests_url

    # 定义一个方法来设置API密钥
    def set_api_key(self, api_key):
        self.api_key = generate_password_hash(api_key)

    # 定义一个方法来解析API密钥

    # 定义一个序列化方法转换为dict
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'base_url': self.base_url,
            'api_key': self.api_key,
            'add_user': self.add_user,
            'requests_url': self.requests_url
        }

    # 定义一个反序列化方法从dict转换
    def from_dict(self, data: dict[str, Any]):
        for field, value in data.items():
            setattr(self, field, value)
